import React from "react";
import {ActivityIndicator, Platform, StyleSheet, Text, TouchableOpacity, View} from "react-native";
import ProcessBar from "./ProcessBar";
import PropTypes from "prop-types";
import {ChatTheme} from "./ChatTheme";
// import {BroadcastEvent} from "../../events/BroadcastEvent";
// import {FileInfo} from "../../libs/sdk/echatim/core/fileclient/FileServerClient";
// import Toast from "../toast/Toast";



class FileMessage extends React.Component {
    constructor(props) {
        super(props);

        // DeviceEventEmitter.addListener(BroadcastEvent.EVENT_FILE_UPLOAD_START, this.onFileStartUpload.bind(this));
        // DeviceEventEmitter.addListener(BroadcastEvent.EVENT_FILE_UPLOADING, this.onFileUploading.bind(this));
        // DeviceEventEmitter.addListener(BroadcastEvent.EVENT_FILE_UPLOADED, this.onFileUploaded.bind(this));

        this.state = {
            hideProcessBar: !this.props.fileIdUploading,
            fileSize: this.props.fileSize,
            send: false
        };
        this.bar = null;
    }

    triggerUploadChange(type, data){
        console.log(`triggerUploadChange, type:${JSON.stringify(type)}, data:${JSON.stringify(data)}`)
        if(type === 'UPLOAD_START'){
            this.onFileStartUpload(data);
        }else if(type === 'UPLOADED'){
            this.onFileUploaded(data);
        }
        else if(type === 'UPLOADING'){
            this.onFileUploading(data);
        }
    }

    onFileStartUpload(info){
        if(this.props.fileIdUploading && this.props.fileIdUploading === info.id){
            this.updateProcessBar(info.uploadPercent + '%');
            this.setState({
                hideProcessBar: false,
                fileSize: info.size,
                send: false
            })
        }
    }

    onFileUploading(info){
        if(this.props.fileIdUploading && this.props.fileIdUploading === info.id){
            this.updateProcessBar(info.uploadPercent + '%');
        }
    }
    onFileUploaded(info){
        if(this.props.fileIdUploading && this.props.fileIdUploading === info.id){
            console.log(`${info.name} upload finish, hide the bar.`);
            this.setState({
                hideProcessBar: true,
                fileSize: info.size,
                send: true
            })
        }
    }

    updateProcessBar(progressPercent) {
        if(!this.bar){
            return;
        }
        this.bar.update(progressPercent)
    }

    getBar(bar){
        this.bar = bar;
        return bar;
    }

    pressFile(){
        if(Platform.OS !== 'web'){
            console.log('暂不支持在android/ios上下载文件.');
            return;
        }
        window.open(this.props.data.body.body);
    }

    render() {
        const { message, messageErrorIcon, isSelf, isOpen, reSendMessage, chatType, showIsRead, isReadStyle, ImageComponent } = this.props
        let name = message.content.name || '';
        let fileSize = message.content.fileSize || this.state.fileSize;
        return (
            <View style={[isSelf ? fileMessageStyles.right : fileMessageStyles.left]}>
                <TouchableOpacity
                    ref={e => (this[`item_${this.props.rowId}`] = e)}
                    activeOpacity={1}
                    collapsable={false}
                    disabled={isOpen}
                    onPress={() => this.props.onMessagePress('file', parseInt(this.props.rowId), message.content.uri, message)}
                    style={{ backgroundColor: 'transparent', padding: 5, borderRadius: 5 }}
                    onLongPress={() => {
                        this.props.onMessageLongPress(this[`item_${this.props.rowId}`], 'file', parseInt(this.props.rowId), message.content.uri, message)
                    }} >
                    <View style={[fileMessageStyles.container, { maxHeight: 300, overflow: 'hidden', borderRadius: 5 }]}>
                        {/*<TouchableOpacity activeOpacity={1} onPress={() => this.pressFile()}>*/}
                            <View style={{flexDirection:'row'}}>
                                <View style={{flex:1, flexDirection:'column'}}>
                                    <Text  numberOfLines={2} ellipsizeMode={'tail'}  style={fileMessageStyles.fileName}>{name}</Text>
                                    <Text style={fileMessageStyles.fileDesc}>{`${fileSize > 0 ? fileSize + 'KB' : '未知大小'}/${this.state.send ? '已发送' : '发送中'}`}</Text>
                                </View>
                                <View>
                                    <View style={fileMessageStyles.fileICON}>
                                        <Text style={fileMessageStyles.fileICONText}>{name.indexOf('.') >=0 ? name.substr(name.lastIndexOf('.') + 1) : '?'}</Text>
                                    </View>
                                </View>
                            </View>
                        {/*</TouchableOpacity>*/}
                        <ProcessBar
                            ref={(bar)=>this.getBar(bar)}
                            initialProgress = {this.props.initialProgress ? this.props.initialProgress+'%' : '0%'}
                            backgroundStyle = {{}}
                            fillStyle = {{backgroundColor:ChatTheme.themeColor}}
                            style = {[fileMessageStyles.processBar, {height:this.state.hideProcessBar ? 0 : 1.5}]} />
                    </View>
                </TouchableOpacity>
                <View style={{ alignItems: 'center', justifyContent: 'center', marginRight: 10 }}>
                    {!isSelf
                        ? null
                        : message.sendStatus === undefined
                            ? null
                            : message.sendStatus === 0
                                ? <ActivityIndicator />
                                : message.sendStatus < 0
                                    ? <TouchableOpacity
                                        disabled={false}
                                        activeOpacity={0.7}
                                        onPress={() => {
                                            if (message.sendStatus === -2) {
                                                reSendMessage(message)
                                            }
                                        }}>
                                        {messageErrorIcon}
                                    </TouchableOpacity>
                                    : null
                    }
                </View>
            </View>
        )
    }
}


const fileMessageStyles = StyleSheet.create({
    right: {
        flexDirection: 'row-reverse',
        marginRight: 10
    },
    left: {
        flexDirection: 'row',
        marginLeft: 10
    },

    container: {
        backgroundColor:'#fff',
        padding:18,
        borderRadius:8,
        flex: 1
    },
    fileName:{
        fontSize:15,
        maxWidth:100
    },
    fileDesc:{
        fontSize:11,
        color:'#B5B5AF',
        marginTop:8
    },
    fileICON:{
        justifyContent:'center',
        alignItems:'center',
        borderWidth:ChatTheme.minBorderWidth,
        borderColor:'#B5B5AF',borderRadius:2,
        backgroundColor:'#FAFAFA',marginLeft:20,
        width:40,
        height:56
    },
    fileICONText:{
        fontSize:16,
        fontWeight:'bold'
    },
    processBar:{
        marginTop:4
    },
    content: {
        flexDirection:'column',
        justifyContent:'space-around',
        marginLeft:6,
        // marginRight:6,
        flexShrink: 1,
        flex:1
    },
});


export default FileMessage;
FileMessage.propTypes = {
    toMe:PropTypes.number,
    name:PropTypes.string,
    fileSize:PropTypes.number,
    initialProgress:PropTypes.number,
    fileIdUploading:PropTypes.string,
    data:PropTypes.any
};

